package org.example.day08;

/**
 * 第三章节3.1.19.1: 一生产-一消费
 */
//生产者
public class MyThread6 {
    private String lock;

    public MyThread6(String lock) {
        this.lock = lock;
    }
    public void setValue(){
        try {
            synchronized (lock){
                if(!ValueObject1.value.equals("")){
                    lock.wait();
                }
                String value = System.currentTimeMillis() + "_" + System.nanoTime();
                System.out.println("set的值是: " + value);
                ValueObject1.value = value;
                lock.notify();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String lock = new String("");
        //生产者
        MyThread6 m6 = new MyThread6(lock);
        //消费者
        C c = new C(lock);
        //生产线程
        Thread6A ta = new Thread6A(m6);
        //消费线程
        Thread6B tb = new Thread6B(c);
        ta.start();
        tb.start();
    }
}

class ValueObject1{
    public static String value = "";
}

//消费者
class C{
    private String lock;

    public C(String lock) {
        this.lock = lock;
    }
    public void getValue(){
        try {
            synchronized (lock){
                if(ValueObject1.value.equals("")){
                    lock.wait();
                }
                System.out.println("get的值是: " + ValueObject1.value);
                ValueObject1.value = "";
                lock.notify();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

//生产者线程
class Thread6A extends Thread{
    private MyThread6 m6;

    public Thread6A(MyThread6 m6) {
        this.m6 = m6;
    }

    @Override
    public void run() {
        while(true){
            m6.setValue();
        }
    }
}

//消费者线程
class Thread6B extends Thread{
    private C c;

    public Thread6B(C c) {
        this.c = c;
    }

    @Override
    public void run() {
        while(true){
            c.getValue();
        }
    }
}